import { message } from 'antd';
import { history } from 'umi';
import Cookie from 'js-cookie';
import { fetchLogin, fetchLogout } from '@/services/login';

const Model = {
  namespace: 'login',
  state: {},
  effects: {
    *requestLogin({ payload }: any, { put, call }: any): any {
      const response = yield call(fetchLogin, payload);
      if (!response.status) {
        message.success('登录成功');
        yield put({
          type: 'setLoginState',
          payload: response,
        });
        history.replace('/');
      } else {
        message.error('登录失败');
      }
    },
    *requestLogout(_: any, { call }: any): any {
      const response = yield call(fetchLogout);
      if (!response.status) {
        Cookie.remove('token');
        message.info('已退出');
        history.replace('/login');
      }
    },
  },
  reducers: {
    setLoginState(state: any, action: any) {
      const { payload } = action;
      Cookie.set('token', payload.access_token);
      return { ...state, ...payload };
    },
  },
};
export default Model;
